import axios from 'axios'

// Return the document's cookies as an object of name/value pairs.
function getCookies() {
  var cookies = {};
  var all = document.cookie;
  if (all === '') return cookies;
  var list = all.split('; ');
  for (var i = 0; i < list.length; i++) {
    var cookie = list[i];
    var p = cookie.indexOf('=');
    var name = cookie.substring(0, p);
    var value = cookie.substring(p + 1);
    value = decodeURIComponent(value);
    cookies[name] = value;
  }
  return cookies;
}

function getCookie(name) {
  var cookies = getCookies()
  var value = ''
  if (cookies && cookies[name]) {
    value = cookies[name]
  }
  return value
}

function clearCookie() {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  document.cookie = 'access_token' + '=;domain=' + window.host.cookieDomain + ';expires=' + exp.toGMTString() + ';path=/'
  document.cookie = 'username' + '=;domain=' + window.host.cookieDomain + ';expires=' + exp.toGMTString() + ';path=/'
  document.cookie = 'language' + '=;domain=' + window.host.cookieDomain + ';expires=' + exp.toGMTString() + ';path=/'
}

// set cookie
function setCookie(name, value) {
  var cookie = name + '=' + encodeURIComponent(value);
  document.cookie = cookie
}

function checkPermission(path) {
  return axios.get(window.permissionCheckUrl + '?', {
    params: {
      requestUrl: path,
      httpMethod: 'GET',
      serviceName: window.host.serviceName,
      type: 'FRONTEND_URL'
    }
  })
}

export default {
  getCookies,
  setCookie,
  checkPermission,
  getCookie,
  clearCookie
};
